package com.aispeech.asr.clib.vad;

import com.sun.jna.Native;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VadSplitter {
    private static IVad iVadSplitter = null;

    public static void initialize() {
        iVadSplitter = Native.load("vad", IVad.class);
        log.info("VadSplitter library loaded.");
    }

    public static String process(String resPath, int pauseTime, int maxSpeechTime, byte[] data, int length) {
        String json = null;
        String config = String.format("{\"pauseTime\":%d,\"maxSpeechTime\":%d}", pauseTime, maxSpeechTime);

        long ptVadSplitter = iVadSplitter.vad_split_new(resPath, 1);

        if (ptVadSplitter <= 0)
            throw new RuntimeException("vad_split_new failed. ptVad: " + ptVadSplitter);

        iVadSplitter.vad_split_reset(ptVadSplitter);
        int ret = iVadSplitter.vad_split_start(ptVadSplitter, config, config.length());
        if (ret != 0)
            throw new RuntimeException(String.format("vad_split_start failed. ptVad: %d, config: %s", ptVadSplitter, config));

        ret = iVadSplitter.vad_split_feed(ptVadSplitter, data, length);
        if (ret != 0) {
            log.warn("[ VadSplitter ] feed err. ret: " + ret);
        }


        PointerByReference result = new PointerByReference();
        IntByReference resultLen = new IntByReference();

        ret = iVadSplitter.vad_split_stop(ptVadSplitter, result, resultLen);
        if (ret == 0 && resultLen.getValue() > 0) {
            json = result.getValue().getString(0);
        } else {
            log.warn("[ VadSplitter ] stop err. ret: {}, result length: {}", ret, resultLen.getValue());
        }

        iVadSplitter.vad_split_delete(ptVadSplitter);

        return json;
    }
}
